package kr.saeildamil.androidstudy_second.fileio;

import java.io.File;
import java.util.ArrayList;

import kr.saeildamil.androidstudy_second.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FileExplorer extends Activity {
	String mCurrent;       //현재경로
	String mRoot;          //mnt/sdcard
	TextView mCurrentTxt;  //현재 경로표시
	ListView mFileList;    //현재 경로상의 파일 정보 리스트
	ArrayAdapter<String> mAdapter;
	ArrayList<String>  arFiles;   //파일정보들
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch25_fileexplorer);
	
		mCurrentTxt =  (TextView) findViewById(R.id.current);
		mFileList = (ListView) findViewById(R.id.filelist);
		
		arFiles = new ArrayList<String>();
		mRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
		mCurrent = mRoot;
		
		mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arFiles);
		mFileList.setAdapter(mAdapter);
		mFileList.setOnItemClickListener(mItemClickListener);
		
		refreshFiles();
	}
	
	public void mOnClick(View v){
		switch(v.getId()){
		case R.id.btnroot:
			if(mCurrent.compareTo(mRoot) != 0){
				mCurrent = mRoot;
				refreshFiles();
			}
			break;
		case R.id.btnup:
			if(mCurrent.compareTo(mRoot) != 0){
				int end = mCurrent.lastIndexOf("/");
				mCurrent = mCurrent.substring(0, end);
				refreshFiles();
			}
			break;
		}
	}
	
	
	private void refreshFiles() {
		mCurrentTxt.setText(mCurrent);
		arFiles.clear();
		File current = new File(mCurrent);  //현재 작어중인 폴더에 있는 파일정보를 얻기위해 File밑에 생성
	
		String[] files = current.list();
		 if(files != null){
			 for(String fileInfo : files){
				 File file = new File(mCurrent + "/" + fileInfo);
				 String Name="";
				 if(file.isDirectory()){
					 Name = "[" + fileInfo + "]";
				 }else{
					 Name = fileInfo;
				 }
				 arFiles.add(Name);
			 }
		 }
		 mAdapter.notifyDataSetChanged();
	}

	AdapterView.OnItemClickListener mItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			String name = arFiles.get(position);
			if(name.startsWith("[") && name.endsWith("]")){
				name = name.substring(1, name.length()-1);
				Toast.makeText(FileExplorer.this, "디렉터리"+name, 1).show();
				mCurrent = mCurrent + "/" + name;
				refreshFiles();
			}else{
				Toast.makeText(FileExplorer.this, name, 1).show();
			
			}
		}
	};
}







